//
//  KDirectoryDetailViewController.m
//  Keping
//
//  Created by 柯平 on 2017/10/11.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KDirectoryDetailViewController.h"
#import "KDirectoryData.h"
#import <SDCycleScrollView.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <GoogleMaps/GoogleMaps.h>
#import "KDirectoryRequest.h"
#import "KPhotoGroupView.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetItem.h>
#import "GPIMController.h"
#import "KYPhotoBrowserController.h"

@interface KDirectoryDetailViewController ()<SDCycleScrollViewDelegate,GMSMapViewDelegate,CLLocationManagerDelegate>
{
    GMSMapView* _mapView;
    MKPointAnnotation *_annotation;
    CLLocationManager *_locationManager;
    CLLocationCoordinate2D _currentLocationCoordinate;
}

/**/
@property(nonatomic,strong)SDCycleScrollView* adView;
/**/
@property(nonatomic,strong)UILabel* countLabel;
/**/
@property(nonatomic,strong)YYLabel* nameLabel;
/**/
@property(nonatomic,strong)YYLabel* addressLabel;
/**/
@property(nonatomic,strong)UIButton* callButton;
@end

@implementation KDirectoryDetailViewController

- (void)actionForShare {
    NSString *shareText = [NSString stringWithFormat:@"%@ \n%@ \n%@",self.model.storeName,self.model.addr,self.model.contact];
    WEAKSELF
    SSUIShareActionSheetItem *item = [SSUIShareActionSheetItem itemWithIcon:[UIImage imageNamed:@"ic_friend"] label:@"Friends" onClick:^{
        GPIMController *vc = [[GPIMController alloc] initWithIndex:1 isShare:YES shareText:shareText];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSArray *array = @[@(SSDKPlatformTypeSMS),item,@(SSDKPlatformTypeWhatsApp)];
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:shareText
                                         images:nil
                                            url:[NSURL URLWithString:@"https://www.linktime.com.my/"]
                                          title:self.model.storeName
                                           type:SSDKContentTypeText];
        //有的平台要客户端分享需要加此方法，例如微博
        [shareParams SSDKEnableUseClientShare];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:array
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateBegin:
                           {
                               UIBarButtonItem* item = [UIBarButtonItem appearance];
                               [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kBlueColor} forState:UIControlStateNormal];
                               [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kBlueColor}];
                               //设置UI等操作
                               break;
                           }
                           case SSDKResponseStateSuccess:
                           {
                               UIBarButtonItem* item = [UIBarButtonItem appearance];
                               [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                               [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Share Success!"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIBarButtonItem* item = [UIBarButtonItem appearance];
                               [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                               [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Share Fail!"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Details";
    [self getData];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shared"] style:UIBarButtonItemStyleDone target:self action:@selector(actionForShare)];
    //广告栏
    _adView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero shouldInfiniteLoop:YES imageNamesGroup:@[]];
    _adView.pageControlDotSize = CGSizeMake(10, 10);

    _adView.pageDotColor = kWhiteColor;
    _adView.currentPageDotColor = kYellowColor;
    _adView.autoScrollTimeInterval = 3.5;
    _adView.delegate = self;
    [_adView setFrame:CGRectMake(0, 0, kScreenWidth, CGFloatPixelRound(200))];

    [self.view addSubview:_adView];
    
    CGFloat WH = CGFloatPixelRound(45);
    CGFloat margin = CGFloatPixelRound(15);
    //图片计算视图
    _countLabel = [[UILabel alloc]init];
    _countLabel.backgroundColor = [UIColor colorWithHexString:@"#393a3e"];
    _countLabel.layer.borderColor = [UIColor colorWithHexString:@"#67686c"].CGColor;
    _countLabel.layer.masksToBounds = YES;
    _countLabel.layer.cornerRadius = WH/2;
    _countLabel.layer.borderWidth = CGFloatPixelRound(2);
    _countLabel.textAlignment = NSTextAlignmentCenter;
    _countLabel.textColor = [UIColor whiteColor];
    _countLabel.text = [NSString stringWithFormat:@"1/%zd",_adView.localizationImageNamesGroup.count];
    [_countLabel setFrame:CGRectMake(_adView.width - WH - margin, _adView.height - WH - margin, WH, WH)];
    [_adView addSubview:_countLabel];
    
    _nameLabel = [YYLabel new];
    _nameLabel.font = SystemBoldFont;
    _nameLabel.textColor = kBlackColor;
    [_nameLabel setFrame:CGRectMake(margin, _adView.bottom+10, kScreenWidth - margin*2, 30)];
    _nameLabel.attributedText = [self nameString:self.model.storeName];
    [self.view addSubview:_nameLabel];
    
    _addressLabel = [YYLabel new];
    _addressLabel.font = SystemSmallFont;
    _addressLabel.textColor = kDarkGrayColor;
    [_addressLabel setFrame:CGRectMake(_nameLabel.left, _nameLabel.bottom, _nameLabel.width, _nameLabel.height)];
    _addressLabel.attributedText = [self addressString:self.model.addr];
    [self.view addSubview:_addressLabel];
    
    _callButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_callButton setFrame:CGRectMake(10, _addressLabel.bottom+margin, kScreenWidth-20, 44)];
    [_callButton setBackgroundImage:[UIImage imageNamed:@"bg_bar"] forState:UIControlStateNormal];
    [_callButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    _callButton.titleLabel.font = SystemBoldFont;
    [_callButton setTitle:self.model.contact?:@"Contact" forState:UIControlStateNormal];
    [_callButton addTarget:self action:@selector(actionForPhone:) forControlEvents:UIControlEventTouchUpInside];
    _callButton.clipsToBounds = YES;
    _callButton.layer.cornerRadius = 3.0;
    [self.view addSubview:_callButton];
    
    
    CGFloat latitude = 0.0;
    CGFloat longitude = 0.0;
    NSString *title = @"";
    NSString *summary = @"";
    if (self.model.longitude > 0 || self.model.latitude > 0) {
        latitude = self.model.latitude;
        longitude = self.model.longitude;
        title = self.model.storeName;
        summary = self.model.summary;
    }else{
        title = @"马来西亚";
        [self startLocation];
    }
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
                                                            longitude:longitude
                                                                 zoom:16];
    CGRect rect = CGRectMake(0, _callButton.bottom+margin*2, kScreenWidth, kScreenHeight - CGRectGetMaxY(_callButton.frame)-margin*2);
    _mapView = [GMSMapView mapWithFrame:rect camera:camera];
    _mapView.delegate = self;
    //显示蓝点圆圈和指南针方向
    _mapView.myLocationEnabled = NO;
    _mapView.mapType = MKMapTypeStandard;
    [self.view addSubview:_mapView];
    
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(self.model.latitude, self.model.longitude);
    marker.title = title;
    marker.snippet = summary;
    marker.map = _mapView;
}

- (void)getData {
    [super getData];
    [self showLoading];
    WEAKSELF
    KDirectoryDetailRequest *request = [[KDirectoryDetailRequest alloc] initWithKey:self.model.id];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        KDirectory* data = [KDirectory modelWithDictionary:[dict objectForKey:@"shopView"]];
        if (status == 200) {
                NSMutableArray* imgs = [NSMutableArray array];
                if (data.imageUrls.count > 0) {
                    NSArray* urls = data.imageUrls;
                    for (NSString* url in urls) {
                        NSString* img = [NSString stringWithFormat:@"%@%@",KGetImageURL,url];
                        [imgs addObject:img];
                    }
                    if (urls.count > 0) {
                        [_adView setImageURLStringsGroup:imgs];
                    }
                }
        }else{
            [self showErrorText:[dict objectForKey:@"msg"] errCode:[[dict objectForKey:@"statusCode"] integerValue]];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

- (IBAction)actionForPhone:(id)sender {
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",self.model.contact];
    NSURL *url = [NSURL URLWithString:str];
     [[UIApplication sharedApplication] openURL:url];
}

- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",@"Link Time",@"googleMap",self.model.latitude, self.model.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 9.0) {
        // 针对 9.0 以上的iOS系统进行处理
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
    } else {
        // 针对 9.0 以下的iOS系统进行处理
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
    
    /* 系统自带的导航
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(self.model.latitude, self.model.longitude) addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                   MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
     */
}

-(void)dealloc
{
    _mapView.delegate = nil;
    _mapView = nil;
}

-(NSMutableAttributedString*)nameString:(NSString*)name{
//    UIImage* nameImg = [UIImage imageNamed:@"store_name_icon"];
//    NSMutableAttributedString* nameImgText = [NSMutableAttributedString imageStringWithFontSize:16 image:nameImg];
    NSMutableAttributedString* text = [[NSMutableAttributedString alloc] init];
//    [text appendAttributedString:nameImgText];
//    [text appendString:@"  "];
    [text appendString:name?:@" "];
    return text;
}

-(NSMutableAttributedString*)addressString:(NSString*)address{
    UIImage* addImg = [UIImage imageNamed:@"address_icon"];
    NSMutableAttributedString* addImgText = [NSMutableAttributedString imageStringWithFontSize:16 image:addImg];
    NSMutableAttributedString* text = [[NSMutableAttributedString alloc] init];
    [text appendAttributedString:addImgText];
    [text appendString:address?:@"  "];
    return text;
}

#pragma mark - SDDelegate
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index
{
    if (cycleScrollView.imageURLStringsGroup.count > 0) {
        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",index+1,cycleScrollView.imageURLStringsGroup.count];
    } else {
        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",index,cycleScrollView.imageURLStringsGroup.count];
    }
}
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    [KYPhotoBrowserController showPhotoBrowserWithImages:cycleScrollView.imageURLStringsGroup currentImageIndex:index delegate:nil];
}

- (void)startLocation
{
    if([CLLocationManager locationServicesEnabled]){
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 5;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//kCLLocationAccuracyBest;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    KLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:oldCoordinate.latitude
                                                            longitude:oldCoordinate.longitude
                                                                 zoom:16];
    [_mapView setCamera:camera];
    [manager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [_locationManager requestWhenInUseAuthorization];
            }
            break;
        case kCLAuthorizationStatusDenied:
        {
        }
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
